package com.yidu.mt.controller;

import com.yidu.mt.controller.vo.MtUserVo;

import com.yidu.mt.service.LogAndRegService;
import com.yidu.mt.utils.BaseMessage;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>@Description: 登录注册</p>
 * <p>@author zhang hao chao</p>
 * <p>@Date: 2021/1/24</p>
 * <p>@Time: 16:58</p>
 */
@Controller
@RequestMapping("/logAndReg")
public class LogAndRegController {

    @Resource
    LogAndRegService logAndRegService;

    @RequestMapping("/log")
    @ResponseBody
    public BaseMessage log(String userName , String userPassword){
        System.out.println("账号是:"+userName+"        ====         密码是"+userPassword);
        int rows = logAndRegService.selectCountNameAndPassword(userName, userPassword);
        System.out.println("返回的行数是:"+rows+"==================");
        return rows==1?BaseMessage.succeed():BaseMessage.noSucceed();
    }

    @RequestMapping("/reg")
    @ResponseBody
    public BaseMessage reg(@RequestParam(value = "userPhoto_", required = false) MultipartFile file,
                            MtUserVo mtUserVo,
                           HttpServletRequest request){

        String fileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName)) {
            int index = fileName.lastIndexOf('.');
            String hz = fileName.substring(index);

            //使用jdk提供的随机字符串
            String newFileName = UUID.randomUUID().toString() + hz;
            //真实路径
            String realPath = request.getServletContext().getRealPath("/upload");
            File target = new File(realPath + "/" + newFileName);
            try {
                //保存文件
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mtUserVo.setUserPhoto("/upload/" + newFileName);
        }
        int rows = logAndRegService.insert(mtUserVo);

        return rows>0? BaseMessage.succeed():BaseMessage.noSucceed();
    }

}
